﻿// *----------------------------------------------------------------
// Copyright (C) 2017 通通优品
// 版权所有。
// 
// 类名：GuidParseModelBinder.cs
// 功能描述：TongTongMall.MallWeb
// 
// Create User：jym 2017/02/09
// 
// Edit User：UserName,EditTime
// Describe：Describe
// ----------------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.ModelBinding;
using TongTongMall.Extensions;
using TongTongMall.MallWeb.Core.Enums;
using TongTongMall.UI;

namespace TongTongMall.MallWeb.WebApi.Core.ModelBinders
{
    /// <summary>
    /// guid绑定内容验证
    /// </summary>
    public class GuidParseModelBinder : IModelBinder
    {
        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            var rawValue = value.RawValue.ToString();

            if (bindingContext.ModelType == typeof(Guid?))
            {
                if (rawValue.IsNullOrEmpty()) return true;
            }
            if (rawValue.IsNullOrEmpty())
            {
                throw new UserFriendlyException((int)ErrCode.ParamErr, "参数类型错误");
            }
            Guid guid;
            if (Guid.TryParse(rawValue, out guid) && guid != Guid.Empty)
            {
                bindingContext.Model = guid;
            }
            else
            {
                throw new UserFriendlyException((int)ErrCode.ParamErr, "参数类型错误");
            }
            
            return true;
        }
    }
}